if exists (select * from dbo.sysobjects where id = object_id(N'[{tableSchema}].[{triggerPrefix}{tableIdentifier}]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
drop trigger [{tableSchema}].[{triggerPrefix}{tableIdentifier}]

exec('
CREATE TRIGGER [{triggerPrefix}{tableIdentifier}]
   ON  [{tableSchema}].[{tableName}]
   AFTER INSERT,UPDATE, DELETE
AS 
BEGIN
	SET NOCOUNT ON;

	-- capture only if insert, delete or update on the column selected for tracking
	IF NOT (EXISTS (select 1 from INSERTED) AND EXISTS (select 1 from DELETED) AND 
		dbo.CdcIsUpdated(columns_updated(), {columnsBitMask})=0) AND 
		(EXISTS (select 1 from INSERTED) OR EXISTS (select 1 from DELETED))
	begin

		DECLARE @ChangeTransactionID as bigint

		INSERT INTO [{dbName}].dbo.[ChangeTransaction]
			(TableName) VALUES (''{tableIdentifier}'')

		set @ChangeTransactionID = scope_identity()

		INSERT INTO [{dbName}].dbo.[{tableIdentifier}_deleted]
			   (ChangeTransactionID		    
				{columnsList}
				)
		SELECT
				@ChangeTransactionID
				{columnsList}
		FROM DELETED


		INSERT INTO [{dbName}].dbo.[{tableIdentifier}_inserted]
			   (ChangeTransactionID
				{columnsList}
				)
		 SELECT
				@ChangeTransactionID
				{columnsList}
		FROM INSERTED

	END

END
')
